import { defineStore } from 'pinia'
import { pinia } from '../index'
import { UserInfo } from '@/api/login/types'
interface LoginState {
  tokenVal: string | null
  userInfo: UserInfo | null
}

export const userLoginState = defineStore('loginState', {
  state: (): LoginState => {
    return {
      tokenVal: null,
      userInfo: null
    }
  },
  getters: {
    tokenKey(): string {
      return 'AccreditId'
    },
    token(): string | null {
      return this.tokenVal
    },
    user(): UserInfo | null {
      return this.userInfo
    },
    sysId(): string | null | undefined {
      return this.userInfo?.CurSubSysId
    }
  },
  actions: {
    setToken(token: string) {
      this.tokenVal = token
    },
    logout() {
      this.tokenVal = null
      this.userInfo = null
    },
    isLogin() {
      return this.tokenVal != null && this.tokenVal != undefined
    },
    setSysId(id: string) {
      if (this.userInfo && id != this.userInfo.CurSubSysId) {
        this.userInfo.CurSubSysId = id
      }
    },
    setUser(user: UserInfo) {
      this.userInfo = user
    }
  },
  persist: true
})

export const loginStateStoreWithOut = () => {
  return userLoginState(pinia)
}
